import type { Canceler} from 'umi-request';
import { extend } from 'umi-request';
import { history, getDvaApp } from 'umi';
import { message, notification } from 'antd';
import { addQueue, removeQueue } from './queue';

/** 异常处理程序 */
const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '',
  400: '请求错误',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '未知请求',
  406: '请求的格式不可得。',
  410: '请求不到资源',
  422: '出现验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};
 
const errorHandler = (error: any) => {
  const { response } = error;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    notification.error({
      message: `请求错误 ${status}`,
      description: errorText,
    });
  }
  //  else if (!response) {
  //   notification.error({
  //     description: '网络异常，无法连接服务器',
  //     message: '网络异常',
  //   });
  // }
  return response;
}

const values: string = window.localStorage.getItem('tokens') || '',
	extendConfig: any = values ? {
		headers: {
			'Authorization': 'bearer ' + values
		}
	} : {};
//对 extend 实例进行简单的封装
const request = extend({
	credentials: 'include',
  timeout: 20000,                    // 超时时间
  headers: extendConfig,
  //处理请求错误 调用上面的错误处理逻辑
  errorHandler: errorHandler,
});

const { CancelToken } = request;
let cancel: Canceler;
request.use((ctx, next) => {
	const { req: { url, options } } = ctx;
	//添加请求队列
	if (addQueue({ url, options }) && !options.cancelToken) {
		options.cancelToken = new CancelToken((c) => {
			cancel = c;
		})
		cancel();
		const errortext = '请勿频繁操作';
		ctx.res = {
			code: -1,
			success: false,
			errMsg: errortext
		};
		return Promise.resolve();
	}
	return next();
})

// 对实例request进行响应拦截, 统一处理接口错误信息
request.interceptors.response.use(async (response, options) => {
	const { url } = options;
	removeQueue({ url, options });
	if (response.status === 200) {
		const data = await response.clone().json();
		if (data && !data.success && data.errCode === 1000) {
			getDvaApp()._store.dispatch({
				type: 'user/clearUser',
			});

			window.localStorage.setItem("backUrl", encodeURIComponent(window.location.href));
			message.error(data.errMsg || '登录失效')
			history.push('/user/login');
			return response;
		}
	}
  return response;
})

export async function req(url: string, options: any) {
	try {
		const value: string = window.localStorage.getItem('tokens') || '',
			exConfig: any = value ? {
				headers: {
					'Authorization': 'bearer ' + value
				}
			} : {};
		const requ = extend(exConfig);
		
		const response: any = await requ(url, options) || {};
		if (response && !response.success && response.errCode === 1000) {
			getDvaApp()._store.dispatch({
				type: 'user/clearUser',
			});

			window.localStorage.setItem("backUrl", encodeURIComponent(window.location.href));
			message.error(response.errMsg || '登录失效')
			history.push('/user/login');
			return {};
		}
		return response;
	} catch (error) {
		console.log('error',error);
	}
}

export default request;